<?php

namespace app\common\model;

use DateTime;
use Serializable;
use think\Model;

/**
 * @property int $id ID
 * @property string $key 配置名
 * @property string $value 配置值
 * @property string $vtype 参数类型
 * @property string $create_at 创建时间
 * @property string $update_at 更新时间
 */
class SystemInfo extends Model
{
    // 数据表名
    protected $table = 'system_info';
    // 主键
    protected $pk = 'id';
    // 保存时自动补完
    protected $auto = [];
    // 新增时自动补完
    protected $insert = [];
    // 更新时自动补完
    protected $update = [];
    // 创建时间字段
    protected $createTime = 'create_at';
    // 更新时间字段
    protected $updateTime = 'update_at';
    // 是否需要自动写入时间戳
    protected $autoWriteTimestamp = true;
    // 类型声明
    protected $type = [
        'id'        => 'integer',
        'key'       => 'string',
        // 'value'     => 'string',
        'vtype'     => 'string',
        'create_at' => 'datetime',
        'update_at' => 'datetime',
    ];

    public function getValueAttr($value, $data)
    {
        $type = $data['vtype'];
        switch ($type) {
            case 'int': $type = 'integer'; break;
            case 'bool': $type = 'boolean'; break;
            case 'string': $type = null; break;
            default: break;
        }
        return $this->readTransform($value, $type);
    }

    public static function set($key, $value)
    {
        $r = static::where('key', $key)->find();
        if (is_int($value)) {
            $type = 'integer';
            $value = (string) $value;
        } else if (is_float($value)) {
            $type = 'float';
            $value = (string) $value;
        } else if (is_bool($value)) {
            $type = 'boolean';
            $value = $value ? '1' : '0';
        } else if (is_object($value)) {
            $type = 'object';
            $value = json_encode($value, JSON_FORCE_OBJECT);
        } else if (is_array($value)) {
            $type = 'json';
            $value  = json_encode($value, JSON_UNESCAPED_UNICODE);
        } else if ($value instanceof Serializable) {
            $type = 'serialize';
            $value = serialize($value);
        } else {
            $type = 'string';
            $value = (string) $value;
        }
        if (!$r) {
            $r = new self([
                'key' => $key,
                'value' => $value,
                'vtype' => $type,
            ]);
        }
        $r->save();
        return $value;
    }

    public static function get($key)
    {
        $r = static::where('key', $key)->find();
        if ($r) {
            return $r->value;
        } else {
            return null;
        }
    }
}
